wGDB = {sellGrays = false}
wGMDB = {}
local wG = "|cffe1a500w|cff69ccf0Gold|cffffffff"
local ldb = LibStub("LibDataBroker-1.1")
local wGold = CreateFrame("Frame", "Broker_wGold")
local realmName = GetRealmName()
local myName = UnitName("player")
local myMoneyTotal,startingGold,merchantGold = 0,0,0

local function moneyFormat(copper, earned)
	local moneyGold = floor(abs(copper / 10000))
	local moneySilver = floor(abs(mod(copper / 100, 100)))
	local moneyCopper = floor(abs(mod(copper, 100)))
	if (earned==1) then -- Gold (earned) tooltip
		if (copper<0) then
			return string.format("|cffff0000 - %d|cffffcc00g |cffff0000%d|cffc0c0c0s |cffff0000%d|cff996600c",moneyGold,moneySilver,moneyCopper)
		elseif (copper>0) then
			return string.format("|cff00ff00 %d|cffffcc00g |cff00ff00%d|cffc0c0c0s |cff00ff00%d|cff996600c",moneyGold,moneySilver,moneyCopper)
		elseif (copper==0) then
			return string.format("%d|cffffcc00g |cffffffff%d|cffc0c0c0s |cffffffff%d|cff996600c",moneyGold,moneySilver,moneyCopper)
		end
	else
		return string.format("|cffffffff%d|cffffcc00g |cffffffff%d|cffc0c0c0s |cffffffff%d|cff996600c",moneyGold,moneySilver,moneyCopper)
	end
end
local function altRemove(alt)
	local name = alt.value
	for k,v in pairs(wGMDB[realmName]) do
		if (k==name) then
			print(string.format("|cffffff00%s has been removed from the %s|cffffff00 database",name,wG))
			wGMDB[realmName][name] = nil
		end
	end
end

-- Choose the day that the weekly data resets on
local function weekDaySelect(self, dayVal)
	UIDropDownMenu_SetSelectedID(menuFrame, self:GetID());
	wGMDB["reset_day"] = dayVal;
end

local menuFrame = CreateFrame("Frame", "menuFrame", UIParent, "UIDropDownMenuTemplate", "MENU")
local alts = {
	--[[{text = "Alt1", value = "1000g"},
	{text = "Alt2", value = "100g"},
	{text = "Alt3", value = "10g"},
	{text = "Alt4", value = "1g"}]]
}
local weekDays = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
local options = {
	{text = "Auto-sell grays", value = "sellGrays", isNotRadio = true, keepShownOnClick = true, func = (function() if (wGDB.sellGrays==false) then wGDB.sellGrays = true else wGDB.sellGrays = false end end)},
	{text = "Remove an alt", value = "altList", notCheck = true, hasArrow = true},
	--{text = "Weekly reset day", value = "dayList", notCheck = true, hasArrow = true},
	{text = nil, value = nil, disabled = true, notCheck = true},
	{text = "Close", value = nil, notCheck = true, keepShowOnClick = false, notCheck = true}
}
local function initialize(self, level)
	local val = UIDROPDOWNMENU_MENU_VALUE
	if (level==1) then
		local title = UIDropDownMenu_CreateInfo()
		title = UIDropDownMenu_CreateInfo()
		title.text = wG
		title.isTitle = true
		title.notCheckable = true
		UIDropDownMenu_AddButton(title, level)
		local info = UIDropDownMenu_CreateInfo()
		for k,v in pairs(options) do
			info = UIDropDownMenu_CreateInfo()
			if (v.disabled~=nil) then info.disabled = v.disabled end
			if (v.notCheck~=nil) then info.notCheckable = v.notCheck end
			if (v.hasArrow~=nil) then info.hasArrow = v.hasArrow info.menuList = v.subMenu end
			if (v.isNotRadio~=nil) then info.isNotRadio = v.isNotRadio end
			if (v.func~=nil) then info.func = v.func end
			info.text = v.text
			info.value = v.value
			info.checked = wGDB[v.value]
			info.keepShownOnClick = v.keepShownOnClick
			UIDropDownMenu_AddButton(info, level)
	   end
	elseif (level==2) then
		local info = UIDropDownMenu_CreateInfo()
		if (val == "altList") then		
			for k,v in pairs(alts) do
				info = UIDropDownMenu_CreateInfo()
				info.text = v.text
				info.value = v.value
				info.func, info.arg1 = altRemove, v.value
				info.isNotRadio = true
				info.notCheckable = true
				UIDropDownMenu_AddButton(info, level)
			end
		elseif (val == "dayList") then
			for k,v in pairs(weekDays) do
				info = UIDropDownMenu_CreateInfo();
				info.text = v;				
				info.func, info.arg1 = weekDaySelect, k;
				info.keepShownOnClick = true
				UIDropDownMenu_AddButton(info, level);
				if (k == wGMDB["reset_day"]) then 				
					UIDropDownMenu_SetSelectedID(menuFrame, k);
				end
			end			
		end
	end
end
UIDropDownMenu_Initialize(menuFrame, initialize, "MENU")
UIDropDownMenu_SetWidth(menuFrame, 100);
UIDropDownMenu_SetButtonWidth(menuFrame, 124)
UIDropDownMenu_JustifyText(menuFrame, "LEFT")



local Broker_wGold = ldb:NewDataObject("Broker_wGold", {
	type = "data source",
	text = "0g 0s 0c",
	icon = "interface\\minimap\\tracking\\auctioneer",
	label = wG,
	OnClick = function(self, button)
		if button == "RightButton" then
			ToggleDropDownMenu(1, nil, menuFrame, self, 0, 15)
		end
	end,
	OnTooltipShow = function(tooltip)
		local moneyTotal = 0
		--[[local moneyToday = 0
		local moneyWeek = 0
		if (wGMDB[realmName]["today_info"]["gold"]~=nil) then moneyToday = moneyFormat((wGMDB[realmName]["today_info"]["gold"] + (GetMoney() - startingGold)),1) else moneyToday = 0 end
		if (wGMDB[realmName]["week_info"]["gold"]~=nil) then moneyWeek = moneyFormat((wGMDB[realmName]["week_info"]["gold"] + (GetMoney() - startingGold)),1) else moneyWeek = 0 end]]
		tooltip:AddLine(wG..":")
		tooltip:AddLine(" ")
		tooltip:AddDoubleLine("Gold earned (this session):", moneyFormat((GetMoney() - startingGold), 1),1,1,1,1,1,1)
		tooltip:AddDoubleLine("Gold earned (today):", moneyFormat((wGMDB[realmName]["today_info"]["gold"] + (GetMoney() - startingGold)),1),1,1,1,1,1,1)
		tooltip:AddDoubleLine("Gold earned (this week):", moneyFormat((wGMDB[realmName]["week_info"]["gold"] + (GetMoney() - startingGold)),1),1,1,1,1,1,1)
		tooltip:AddLine("________________________")
		tooltip:AddLine(" ")
		for k,v in pairs(wGMDB[realmName]) do
			if (k~=nil) and(k~="today_info") and (k~="week_info") then
				tooltip:AddDoubleLine(k..":", (moneyFormat(v)),1,1,1,1,1,1)
				moneyTotal = moneyTotal + v
			end
		end
		tooltip:AddLine("________________________")
		tooltip:AddLine(" ")
		tooltip:AddDoubleLine("Total:", moneyFormat(moneyTotal),1,1,1,1,1,1)
		tooltip:AddLine(" ")
		tooltip:AddLine("|cff69ccf0Right-Click|cffffd200 for options")
	end,
})

local function moneyUpdate()
	myMoneyTotal = GetMoney()
	local dateInfo = date("*t")
	Broker_wGold.text = (moneyFormat(myMoneyTotal))
	if (wGMDB["reset_day"] == nil) then wGMDB["reset_day"] = 1 end; -- Sunday
	if (wGMDB[realmName]==nil) then wGMDB[realmName] = {} end
	wGMDB[realmName][myName] = GetMoney()
	if (wGMDB[realmName]["today_info"]==nil) then wGMDB[realmName]["today_info"] = {} end
	if (wGMDB[realmName]["today_info"]["gold"]==nil) then wGMDB[realmName]["today_info"]["gold"] = 0 end
	if (wGMDB[realmName]["today_info"]["date"]~=(dateInfo.month.."-"..dateInfo.day.."-"..dateInfo.year)) then wGMDB[realmName]["today_info"]["gold"] = 0 end
	if (wGMDB[realmName]["week_info"]==nil) then wGMDB[realmName]["week_info"] = {} end
	if (wGMDB[realmName]["week_info"]["gold"]==nil) then wGMDB[realmName]["week_info"]["gold"] = 0 end
	if (wGMDB[realmName]["week_info"]["gold"]==0) and (wGMDB[realmName]["today_info"]["gold"]~=0) then wGMDB[realmName]["week_info"]["gold"]=wGMDB[realmName]["today_info"]["gold"] end
	if (wGMDB[realmName]["week_info"]["day"]==nil) then wGMDB[realmName]["week_info"]["day"] = dateInfo.wday end
	if (wGMDB[realmName]["week_info"]["day"]>dateInfo.wday) then wGMDB[realmName]["week_info"]["gold"] = 0 end
	wGMDB[realmName]["week_info"]["day"] = dateInfo.wday
	wGMDB[realmName]["today_info"]["date"]  = (dateInfo.month.."-"..dateInfo.day.."-"..dateInfo.year)
	
	
	--if (wGMDB[realmName]["week_info"]["day"] ~= nil) then
	--	if (wGMDB[realmName]["week_info"]["day"] ~= dateInfo.wday and dateInfo.wday == wGMDB["reset_day"]) then
	--		wGMDB[realmName]["week_info"]["day"] = dateInfo.wday;
	--		wGMDB[realmName]["week_info"]["gold"] = 0;
	--	end
	--end
	
	
end

local OnEvent = CreateFrame("Frame")
OnEvent:RegisterEvent("PLAYER_ENTERING_WORLD")
OnEvent:SetScript("OnEvent", function(self, event, arg1, arg2, arg3)
	if (event=="ADDON_LOADED") then
		if (arg1=="Broker_wGold") then
			moneyUpdate()
			for k,v in pairs(wGMDB[realmName]) do
				if (k~=nil) and (k~=myName) and (k~="today_info") and (k~="week_info") then
					table.insert(alts, {text = k, value = k})
				end
			end
		end
	elseif (event=="PLAYER_ENTERING_WORLD") or (event=="PLAYER_MONEY") then
		moneyUpdate()
	elseif (event=="PLAYER_LOGIN") then
		startingGold = GetMoney()
	elseif (event=="PLAYER_MONEY") then
		moneyUpdate()
	elseif (event=="PLAYER_LOGOUT") then
		wGMDB[realmName]["today_info"]["gold"] = (wGMDB[realmName]["today_info"]["gold"] + (myMoneyTotal - startingGold))
		wGMDB[realmName]["week_info"]["gold"] = (wGMDB[realmName]["week_info"]["gold"] + (myMoneyTotal - startingGold))
	elseif (event=="MERCHANT_SHOW") then
		merchantGold = GetMoney()
		if (wGDB.sellGrays==true) then
			local sold = false
			local earned = 0
			for bagNum = 0,4 do
				for slotNum = 1,GetContainerNumSlots(bagNum) do
					local item = GetContainerItemLink(bagNum, slotNum)
					--if (item) and (string.find(item, "ff9d9d9d")) then --Look for gray
					if (item) then
						local _,_,qual,_,_,_,_,_,_,_,vend = GetItemInfo(item)
						if (qual==0) then
							PickupContainerItem(bagNum, slotNum)
							PickupMerchantItem()
							earned = earned + vend
							sold = true
						end
					end
				end
			end
			if (sold==true) then
				print(string.format("%s: Some gray quality items have been automatically sold for %d",wG,moneyFormat(earned)))
			end
		end
	end
end)
OnEvent:RegisterEvent("ADDON_LOADED")
OnEvent:RegisterEvent("PLAYER_LOGIN")
OnEvent:RegisterEvent("PLAYER_MONEY")
OnEvent:RegisterEvent("PLAYER_LOGOUT")
OnEvent:RegisterEvent("MERCHANT_SHOW")